//201902104047周润恺
package filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import util.JWTHelper;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginFilter",urlPatterns = {"/basic/*"})
public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.trace("启动token验证过滤器");
        //强制类型转换
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        try {
            String url = httpServletRequest.getRequestURI();
            log.trace(url);
            String b = "" + url.contains("/login");
            log.trace(b);
            if (!url.contains("/login")){
                //获得请求的token
                String token = httpServletRequest.getHeader("token");
                //解析token
                JWTHelper.verify(token);
                //执行过滤器链
                chain.doFilter(request,response);
                log.trace("Token过滤器结束");
            }
            String token = httpServletRequest.getHeader("token");
            JWTHelper.verify(token);
            chain.doFilter(request,response);
            log.trace("Token过滤器结束");
        } catch (SignatureVerificationException e){
            log.error(e.getMessage());
            message.put("message","签名不一致");
        } catch (TokenExpiredException e){
            log.error(e.getMessage());
            message.put("message","令牌过期");
        } catch (AlgorithmMismatchException e){
            log.error(e.getMessage());
            message.put("message","算法不一致");
        } catch (InvalidClaimException e){
            log.error(e.getMessage());
            message.put("message","失效的payload");
        } finally {
            //响应respMessage_jsonObj到前端
            httpServletResponse.getWriter().println(message);
        }
    }
}
